<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of News
 *
 * @author Soul_man
 */
class Page extends X3_Module_Table {

    public $encoding = 'UTF-8';
    /*
     * uncomment if want new model functional
     */
    public $tableName = 'data_page';
    public static $parent = array();
    
    public $_fields = array(
        'id'=>array('integer[10]','unsigned','primary','auto_increment'),
        'parent_id'=>array('integer[10]','unsigned','index','default'=>'NULL','ref'=>array('Page','id','default'=>'title')),
        'theme_id'=>array('integer[10]','unsigned','index','default'=>'NULL','ref'=>array('Theme','id','default'=>'title')),
        'title'=>array('string[255]'),
        'name'=>array('string[255]','unique'),
        'music'=>array('text','default'=>'NULL'),
        'text'=>array('fulltext','default'=>''),
        'status'=>array('boolean','default'=>'1'),
        'createmenu'=>array('boolean','default'=>'1'),
        'created_at'=>array('integer[10]','unsigned','default'=>'0'),
        //'metatitle'=>array('string','default'=>'','language'),
        //'metakeywords'=>array('string','default'=>'','language'),
        //'metadescription'=>array('string', 'default'=>'','language'),
    );

    public static function newInstance($class=__CLASS__) {
        return parent::newInstance($class);
    }
    public static function getInstance($class=__CLASS__) {
        return parent::getInstance($class);
    }
    public static function get($arr=array(),$single=false,$class=__CLASS__) {
        return parent::get($arr,$single,$class);
    }
    public static function getByPk($pk,$class=__CLASS__) {
        return parent::getByPk($pk,$class);
    }
    public static function update($fields, $params = array(), $class = __CLASS__) {
        return parent::update($fields, $params, $class);
    }
    public static function delete($params = array(), $class = __CLASS__) {
        return parent::delete($params, $class);
    }
    public static function deleteByPk($pk, $class = __CLASS__) {
        return parent::deleteByPk($pk, $class);
    }
    public static function num_rows($params = array(), $class = __CLASS__) {
        return parent::num_rows($params, $class);
    }
    
    public function fieldNames() {
        return array(
            'parent_id'=>'Относится к',
            'theme_id'=>'Тема',
            'createmenu'=>$this->id>0?'Не удалять меню':'Создать пункт меню',
            'title'=>'Заголовок',
            'text'=>'Содержание',
            //'weight'=>'Порядок',
            'name'=>'Имя в URL',
            'status'=>'Видимость',
            'music'=>'Музыка',
            //'metatitle'=>'Metatitle',
            //'metakeywords'=>'Metakeywords',
            //'metadescription'=>'Metadescription',
        );
    }
    
    public function filter() {
        return array(
            'allow'=>array(
                '*'=>array('show'),
                'admin'=>array('show','add','delete','doc','docstatus'),
            ),
            'deny'=>array(
                '*'=>array('add','delete','doc','docstatus')
            ),
            'handle'=>'redirect:/'
        );
    }
    
    public function moduleTitle() {
        return 'Текстовые страницы';
    }

    public function cache() {
        return array(
            //'cache'=>array('actions'=>'show','role'=>'*','expire'=>'+1 day'),
            'nocache'=>array('actions'=>'*','role'=>'admin')
        );
    }
    
    public function getLink() {
        return "/page:$this->name.html";
    }

    public function actionRestore(){
        if(!X3::user()->isAdmin() || !isset($_GET['id']))
            throw new X3_404();
        $id = (int)$_GET['id'];
        $model = Page_History::restore($id);
        $this->redirect($model->getLink());
    }
    
    public function actionHistory(){
        if(!X3::user()->isAdmin() || !isset($_GET['id']))
            throw new X3_404();
        $id = $_GET['id'];
        $this->template->render('history',array('models'=>Page_History::get(array('@condition'=>array('page_id'=>$id),'@order'=>'created_at DESC')),'page'=>Page::getByPk($id)));
    }
    
    public function actionList(){
        if(!X3::user()->isAdmin())
            throw new X3_404();
        $this->template->render('list',array('models'=>Page::get(array())));
    }
    
    public function actionShow(){
        $name = X3::db()->validateSQL($_GET['name']);
        $model = $this->table->select('*')->where("`name`='$name'")->asObject(true);
        if($model==null) throw new X3_404();
        if($model->theme_id>0 && NULL!==($theme = Theme::getByPk($model->theme_id))){
            X3::app()->theme = array(
                'mainheader'=>$theme->mainheader?"/uploads/Theme/".$theme->mainheader:'/images/header.gif',
                'header'=>$theme->header?"/uploads/Theme/".$theme->header:'/images/hr01.png',
                'menutile'=>$theme->menutile?"/uploads/Theme/".$theme->menutile:'/images/menutile.gif',
                'menuheader'=>$theme->menu?"/uploads/Theme/".$theme->menu:'/images/menuheader.gif',
                'cover'=>$theme->cover?"/uploads/Theme/".$theme->cover:'/images/page_background.jpg',
                'back'=>$theme->back?"/uploads/Theme/".$theme->back:'/images/bg1.png',
                'columntile'=>$theme->maintile?"/uploads/Theme/".$theme->maintile:'/images/dekor.jpg',
                'decor'=>$theme->decorations == 1,
            );
        }
        SeoHelper::setMeta($model->title.' - Давидсбюндлеры', $model->title . ', Давидсбюндлеры, Davidsbuendler', $model->title . ', Давидсбюндлеры, Davidsbuendler');
        X3::app()->page_id = $model->id;
        $this->template->render('show',array('model'=>$model));
    }
    
    public function actionChildren() {
        if(!X3::user()->isAdmin() || !IS_AJAX || !isset($_GET['id']))
            throw new X3_404();
        $id = (int)$_GET['id'];
        if($id == 0)
            $models = X3::db()->query("SELECT id, title FROM data_page WHERE parent_id IS NULL");
        else
            $models = X3::db()->query("SELECT id, title FROM data_page WHERE parent_id=$id");
        $pages = array();
        while($model = mysql_fetch_assoc($models))
            $pages[$model['id']] = array('title'=>$model['title'],'selected'=>false);
        echo json_encode($pages);
        exit;
    }
    
    public function actionDocstatus(){
        var_dump($_REQUEST);exit;
    }
    
    public function actionDoc(){
        $file = new Upload('file');
        if($file->message!=false)
            throw new X3_Exception($file->message);
        $filename = $file->filename;
        $this->template->layout = null;
        $x=  X3_Widget::run('@views:page:doc.php',array('file'=>$file));
        $ch = new X3_Thread("http://api.online-convert.com/queue-insert",array('queue'=>$x));
//        $ch = new X3_Thread("http://davids.soulman.kz/page/docstatus",array('queue'=>$x));
//        $ch->setContentType('multipart/form-data');
        $ch->run();
        $response = $ch->getBody();
        
        X3::user()->docHash = $response;
        echo $response;exit;
        $ch = curl_init("http://api.online-convert.com/queue-status");
        $request = array('queue'=>$this->template->renderPartial('doc_status',array('hash'=>$response),true));
    }
    
    public function actionAdd() {
        $page = null;
        if(!X3::user()->isAdmin())
            throw new X3_404();
        if(isset($_GET['id'])){
            $page = Page::getByPk((int)$_GET['id']);
        }
        if($page == null){
            $page = new Page();
        }else {
            X3::app()->page_id = $page->parent_id;
        }
        if(isset($_GET['theme_id'])){
            $page->theme_id = (int)$_GET['theme_id'];
        }
        if(isset($_GET['parent_id'])){
            $page->parent_id = (int)$_GET['parent_id'];
            if($page->theme_id == null && !isset($_POST['Page']))
                $page->theme_id = self::findParentTheme($page->parent_id);
        }
        if(isset($_POST['Page'])){
            $new = false;
            $page->acquire($_POST['Page']);
            if($page->id>0)
                $page->getTable()->setIsNewRecord(false);
            else
                $new = true;
            if($page->save()){
                if(($new && $page->createmenu) || (!$new && NULL===Menu::get(array('page_id'=>$page->id),1))){
                    $menu = new Menu;
                    if($page->parent_id>0){
                        $menu->role = 'submenu';
                    }else{
                        $menu->role = 'menu';
                        $max = X3::db()->fetch("SELECT MAX(weight) AS `max` FROM data_menu WHERE role='menu'");
                        $menu->weight = $max['max'] + 1;
                    }
                    $menu->title=$page->title;
                    $menu->link='/page:'.$page->name.'.html';
                    $menu->page_id = $page->id;
                    $menu->save();
                }elseif(!$new && !$page->createmenu){
                    Menu::delete(array('page_id'=>$page->id));
                }
                $this->redirect("/page/add/id/$page->id");
            }
        }
        $this->template->render('form',array('model'=>$page));
    }
    
    public function actionDelete(){
        if(!isset($_GET['id']) || ($id = (int)$_GET['id'])<=0 || NULL === ($model = Page::getByPk($id))){
            throw new X3_404();
        }
        if($model->parent_id > 0){
            $parent = Page::getByPk($model->parent_id);
            $url = $parent->getLink();
        }else
            $url = '/';
        Page::deleteByPk($model->id);
        if(IS_AJAX)
            echo 'OK';
        $this->redirect($url);
        exit;
    }
    
    public function parentM() {
        if(!isset(self::$parent[$this->parent_id]))
            self::$parent[$this->parent_id] = Page::getByPk($this->parent_id);
        return self::$parent[$this->parent_id];
    }
    
    public function menu() {
        /*if(isset($_GET['parent_id'])){
            $current = $_GET['parent_id'];
            $html = array('<a href="/admin/page/"><b>Все</b></a>');
        }else{
            $current = -1;
            $html = array('<span><b>Все</b></span>');
        }
        if($current == 0)
            $html []= '<span>Верхний уровень</a>';
        else
            $html []= '<a href="/admin/page/parent_id/0">Верхний уровень</a>';
        if($current>0){
            $html []= "<span>$this->short_title</span>";
        }
        return implode(' &gt; ', $html);*/
    }
    
    public function drawChildren(){
        $models = X3::db()->query("SELECT m.id, m.title, m.link FROM data_menu m INNER JOIN data_page p ON p.id=m.page_id WHERE m.status AND p.parent_id='$this->id' ORDER BY m.weight");
        $html = '';
        if(is_resource($models) && mysql_num_rows($models)>0){
            $html = '<div class="parents"><ul>';
            while($model = mysql_fetch_assoc($models)){
                $html .= '<li><a '.(X3::user()->isAdmin()?'menuid="'.$model['id'].'" x3editable="Menu('.$model['id'].').title"':'').' href="'.$model['link'].'">'.$model['title'].'</a></li>';
            }
            $html .= '</ul></div>';
        }
        return $html;
    }
    
    public static function findParentTheme($parent_id){
        $q = X3::db()->fetch("SELECT theme_id, parent_id FROM data_page WHERE id='$parent_id'");
        if($q && $q['theme_id']>0)
            return $q['theme_id'];
        elseif($q == null || $q['parent_id']==null)
            return null;
        return self::findParentTheme($q['parent_id']);
    }
    
    public function generateBread(){
        $html = '';
        $parent_id = $this->parent_id;
        $as = array();
        while($parent_id>0 && null!=($q = X3::db()->fetch("SELECT p.parent_id, m.title, m.link, p.name FROM data_menu m INNER JOIN data_page p ON p.id=m.page_id WHERE m.status AND p.id='$parent_id'"))){
            array_unshift($as, '<a href="'.$q['link'].'">'.X3_Html::encode($q['title']).'</a>');
            $parent_id = $q['parent_id'];
        }
        array_unshift($as, '<a href="/">Главная страница</a>');
        if(($c = count($as))>0){
            if($c>5){
                foreach ($as as $i=>$a) {
                    if($i>1 && $i<$c-2){
                        if($i == 2) 
                            $a[$i] = '<i>...</i>';
                        else
                            unset($as[$i]);
                    }
                }
            }
            $html = implode('<span>&gt;</span>',$as);
        }
        return $html;
    }
    
    public function getDefaultScope() {
        $query = array('@order'=>'title, created_at DESC');
        return $query;
    }
    
    public function onDelete($tables, $condition) {
        if (strpos($tables, $this->tableName) !== false) {
            $model = $this->table->select('*')->where($condition)->asObject(true);
            X3::db()->query("DELETE FROM data_menu WHERE page_id=$model->id");
        }
        parent::onDelete($tables, $condition);
    }    

    public function beforeValidate() {
        if($this->created_at == 0)
            $this->created_at = time();
        if($this->name == ''){
            $name = new X3_String($this->title);
            $name = preg_replace("/[^a-zA-Z0-9\_\-]/", '', $name->translit());
            $name = str_replace("_", '-', $name);
            $this->name = strtolower($name);
        }
        if($this->parent_id=="" || $this->parent_id=="0") $this->parent_id = NULL;
    }
    
    public function afterSave($bNew = false) {
        Menu::update(array('link'=>'/page:'.$this->name.'.html'),array('page_id'=>$this->id));
        $oldtimes = time() - 2592000; // 30 days
        Page_History::delete(array('created_at'=>array('<'=>$oldtimes)));
        Page_History::add($this,md5($this->text));
        parent::afterSave($bNew);
    }

}
?>
